package com.monco.push;

import com.monco.bean.RedisBean;
import com.monco.config.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: monco
 * @Date: 2019/5/24 15:54
 * @Description: <p>
 * 将主要排序的队列进行序列化 存储方式为redis + mysql
 * 队列采用 redis的list存储
 * list中每个key值为对象的序列化 也就是消息体
 * 采用kryo序列化工具
 */
@Slf4j
@RestController
public class PushController {

    @Autowired
    private RedisService redisService;

    @PostMapping("push")
    public void pushQueue(@RequestBody RedisBean redisBean) {
        StringBuilder builder = new StringBuilder();
        builder.append(redisBean.getQueueName()).append("-");
        if (redisService.hasKey(redisBean.getQueueName())) {
            // 获得list最后一个key
            String key = (String) redisService.lGetIndex(redisBean.getQueueName(), -1);
            // 获得最后一个key的序号
            Integer number = Integer.valueOf(key.split("-")[1]);
            builder.append(number + 1);
        } else {
            builder.append(1);
        }
        log.info("已初始化redis队列，key值" + redisBean.getQueueName());
        redisService.lSet(redisBean.getQueueName(), builder.toString());
        if (redisService.lGetListSize(redisBean.getQueueName()) == 1) {
            redisService.set(builder.toString(), redisBean.getContent(), 30);
            log.info("第一个任务已经入队，30秒之后启动监听……");
        } else {
            redisService.set(builder.toString(), redisBean.getContent());
            log.info("排队任务已经入队，key=" + builder.toString() + ",value 为" + redisBean.getContent());
        }
    }

    @PostMapping("pop")
    public void popQueue(@RequestBody RedisBean redisBean) {
        log.info("收到回调》》》 返回成功");
        String dataKey = (String) redisService.lGetIndex(redisBean.getQueueName(), 0);
        log.info("取得需要删除的key" + dataKey);
        redisService.del(dataKey);
        log.info("删除完成");
        if (redisService.hasKey(redisBean.getQueueName())) {
            Object o = redisService.lLeftPop(redisBean.getQueueName());
            log.info("获得redis移除结果" + o);
        }
        dataKey = (String) redisService.lGetIndex(redisBean.getQueueName(), 0);
        log.info("拿到下一次发送消息体的key值" + dataKey);
        if (StringUtils.isNotBlank(dataKey)) {
            String content = (String) redisService.get(dataKey);
            log.info("发送内容" + content);
            redisService.expire(dataKey, 30);
        }

    }
}



